#!/usr/bin/env python
#coding:utf-8
import tornado.web
import json
import motor
from bson import ObjectId


class BaseHandler(tornado.web.RequestHandler):
    Status = True
    dbClient = None
    status = 200
    msg = 'ok'
    #access登陆验证

    def __init__( self, *args, **kwargs ):
            # 继承于 tornado.web.RequestHandler
        tornado.web.RequestHandler.__init__( self, *args, **kwargs )



    def check_access(self):
        if 'X-Access-Code' not in self.request.headers:
            return self.response_msg(403,'Forbbiden Access')
        if 'X-Access-Key' not in self.request.headers:
            return self.response_msg(403,'Forbbiden Access')
        #此处可以添加后期的登录控制
        if self.request.headers['X-Access-Code'] != u'123456':
            return self.response_msg(402,'Access Denied')
        if self.request.headers['X-Access-key'] != u'ABCDEF':
            return self.response_msg(402,'Access Denied')

    #同一返回消息接口
    def response_msg(self,code=200,msg=None,data=[],count=False):
        #设置返回的response头信息
        self.Status = False
        #self._headers = {'Content-type':'application/json'}
        self.set_header("Content-Type", "application/json")
        #组装返回信息
        responseInfo = {}
        if code:
            responseInfo['code'] = code
        if msg:
            responseInfo['message'] = msg
        if data:
            responseInfo['results'] = data
        if count:
            responseInfo['count'] = count
        self.write(json.dumps(responseInfo))
        self.finish()



    #对mongo返回的结果进行格式化，去掉ObjectId
    def find_formart(self,cousor):
        info = []
        print(456)
        for e in cousor:
            e['objectId'] = str(e['_id'])
            e.pop('_id')
            info.append(e)
        return  info

    def log(self,data):
        if isinstance(data,str):
            info = []
            info.append({'message':data})
        self.response_msg(200,'debug',data)